/*
 * @Author       : lg
 * @Date         : 2022-06-24 22:48:08
 * @LastEditors  : lg
 * @LastEditTime : 2022-06-24 22:57:39
 * @FilePath     : \TwoWeeksFaceTest\ws-server\server\ws.p2p.js
 * @description  :
 */
// 获得服务的类
const { WebSocketServer } = require("ws");
// 创建实例
const wsServer = new WebSocketServer({ port: 3000 });
// 保存多个窗口client的ws连接
const userList = [];
const userMsgMap = {};
const list = {};
// 监听连接事件
wsServer.on("connection", (curWs) => {
  // 连接成功
  curWs.on("message", (msg) => {
      const rawData = JSON.parse(msg.toString());
      // console.info("ws server received message", rawData);
      // 关闭连接
      if (rawData.close) {
        list[rawData.event] && list[rawData.event].close();
        list[rawData.event] = null;
        delete list[rawData.event];
        userList.splice(userList.findIndex((item) => item.id === rawData.event), 1);
        userList.forEach((item) => {
          list[item.id] && list[item.id].send(JSON.stringify({
            code: 201,
            msg: "更新用户列表！",
            event: item.id,
            data: { userList },
          }));
        });

        return;
      }

      // 保存用户的ws连接
      if (!list[rawData.event] || list[rawData.event] !== curWs) {
        list[rawData.event] && list[rawData.event].close();
        list[rawData.event] = curWs;
        userList.findIndex((item) => item.id === rawData.event) === -1 && userList.push(rawData.data.user);
        console.log("当前用户列表：", userList);
        userList.forEach((item) => {
          list[item.id] && list[item.id].send(JSON.stringify({
            code: 201,
            msg: "更新用户列表！",
            event: item.id,
            data: { userList },
          }));
        });
      }

      if (!rawData.data.from || !rawData.data.to || !rawData.data.content) return;

      rawData.msg = "更新成功！";
      rawData.code = 200;
      rawData.data.id = new Date().getTime();

      const fromData = Object.assign(rawData, { event: rawData.data.from.id });
      list[rawData.data.from.id].send(JSON.stringify(fromData));

      const toData = Object.assign(rawData, { event: rawData.data.to.id });
      list[rawData.data.to.id].send(JSON.stringify(toData));
    },
  );
});
